/**
 * 再图层上画出现应的点、线、面
 * Created by Administrator on 2017/7/14 0014.
 */
$(function () {

    // 能够开始编辑地图的最小缩放级别，小于该级别地图表示的范围太大，精度不够，不能编辑
    var minZoom = 14;
    // 当前是否为可绘制状态
    var canDrawAble = false;
    // 当前画笔状态,是否正在绘制
    var is_drawing = false;
    // 画笔
    var draw;
    // 当前形状
    var draw_type;
    // 当前要素
    var currentFeature = null;

    var select = new ol.interaction.Select({
        wrapX: false,
        layers: [featureOverlay]
    });
    var modify = new ol.interaction.Modify({
        deleteCondition: function (event) {
            return ol.events.condition.shiftKeyOnly(event) &&
                ol.events.condition.singleClick(event);
        },
        pixelTolerance: 20,
        features: select.getFeatures()
    });

    /**----------------------------------地图控件事件---------------------------------------*/
    {
        /*
         监听视图的缩放
         */
        view.on('change:resolution', function (e) {
            var zoom = view.getZoom();
            if (zoom % 1 === 0) {
                switch (true) {
                    case zoom < minZoom:
                        break;
                    case zoom >= minZoom:
                        break;
                }
            }
        });
        /**
         * 选中要素事件
         */
        select.on('select', function (e) {
            console.log("触发选中事件");
            var selected = select.getFeatures();
            console.log('选中' + selected.getLength());
            if (selected.getLength() > 0) {
                $('#delete').removeClass('disabled');
            } else {
                $.publish("delete:off");
            }
            if (selected.getLength() == 1) {
                var feature = select.getFeatures().getArray()[0];
                // 显示要素属性
                showFeatureProperties(feature);
            } else {
                featurePanelHide();
            }
        });

        /**
         * 修改开始
         */
        modify.on('modifystart', function (e) {
            console.log('修改开始');
            var features_ = e.features;
            var geometryArrary = features_.getArray();
            var geometrys = geometryArrary.map(function (item) {
                var geometry = item.getGeometry();
                var type = geometry.getType();
                console.log(type);
                return geometry;
            });
            console.log(geometrys);
        });

        /**
         * 修改结束
         */
        modify.on('modifyend', function (e) {
            console.log('修改结束');
            // TODO 保存操作记录，方便回退操作
            var features_ = e.features.getArray()[0];

            setFeatureGpsType(features_);

            getLength(features_);
            // 保存到缓存
            $.publish("features:save");
        });
    }


    /**----------------------------------订阅信号---------------------------------------*/
    {
        /*
         开始删除操作
         */
        $.subscribe("delete:off", function (e) {
            var Jdelete = $('#delete');
            if (!Jdelete.hasClass('disabled')) {
                Jdelete.addClass('disabled')
            }
            featurePanelHide();
        });

        /*
         开始选择
         */
        $.subscribe("select:on", function (e) {
            if (features.getLength() > 0) {
                map.addInteraction(select);
                map.addInteraction(modify);
            }
        });

        /*
         禁用绘制按钮功能
         */
        $.subscribe("draw:off", function (e) {
            console.log('draw:off');
            // 取消点击事件
            $('#tools').off('click', '.J_type');
            // 设置不可编辑状态
            canDrawAble = false;
            // 设置按钮样式
            var btn = $('#tools').find('.J_type');
            if (!btn.hasClass("disabled")) {
                btn.addClass("disabled");
            }
            btn.removeClass("active");
            removeInteractions();
        });

        /*
         开启绘制按钮功能
         */
        $.subscribe("draw:on", function (e) {
            // 设置可编辑状态
            canDrawAble = true;
            // 设置按钮可编辑样式
            $('#tools').find('.J_type').removeClass("disabled");
            // 设置按钮事件
            $('#tools').on('click', '.J_type', function (e) {
                $(this).siblings().removeClass('active');
                $(this).toggleClass("active");
                var value = $('.J_type.active').val();
                addInteraction(value);
            });
        });

        /*
         开启保存按钮功能
         */
        $.subscribe("save:on", function (e) {
            $('.save').removeClass("disabled").off('click');
            // 设置按钮事件
            $('#save').on('click', function (e) {
                save(false);
            });
            $('#save-publish').on('click', function (e) {
                save(true);
            });
        });
        /*
         关闭保存按钮功能
         */
        $.subscribe("save:off", function (e) {
            $('.save').addClass("disabled");
            // 取消按钮事件
            $('.save').off('click');
        });

        /*
         按下esc键
         1、当前处于绘制状态，那么结束绘制；
         2、没有在绘制状态，但是已设置画笔
         */
        $.subscribe("escape:up", function (e) {
            if (is_drawing) {
                draw.finishDrawing();
            }
            if (canDrawAble) {
                $('#tools').find('.J_type.active').trigger('click');
            }
        });

        /**
         * 关闭要素编辑面板
         */
        $.subscribe("featurePanel:hide", function (e) {
            featurePanelHide();
        });

        /**
         * undo（撤销）
         */
        $.subscribe("undo", function (e) {
            if (is_drawing) {
                draw.removeLastPoint();
            }
        });

        /**
         *  redo(重做)
         */
        $.subscribe("redo", function (e) {
            featurePanelHide();
        });

        /**
         * 删除要素
         */
        $.subscribe("feature:delete", function (e) {
            var source = featureOverlay.getSource();
            var selectedFeatures = select.getFeatures().getArray();
            if (selectedFeatures && selectedFeatures.length > 0) {
                for (var i = selectedFeatures.length - 1; i >= 0; i--) {
                    // 移除要素
                    source.removeFeature(selectedFeatures[i]);
                }
            }
            // 清除选中要素状态
            select.getFeatures().clear();
            // 刷新图层
            source.refresh();
            $.publish("delete:off");
        });

        /**
         * 要素编辑面板输入框的值发生改变
         */
        $.subscribe("input:change", function (e) {
            var property = arguments[1];
            currentFeature.set(property.key, property.value);
            // 更新缓存
            $.publish("features:save");
            /**
             * 更新样式
             */
            // 1、线样式
            updateFeatureStyle(currentFeature);
            // 2、文字样式
            updateContentStyle(currentFeature);

        });
    }
    /**--------------------------------------发布信号--------------------------------------*/
    {
        $.publish("draw:on");
    }

    /**----------------------------------函数定义---------------------------------------*/

    /**
     * 设置画笔
     * @param type
     */
    function addInteraction(type) {
        removeInteractions();
        if (!type) {
            // 结束绘制，增加选中要素控件
            $.publish('select:on');
            return;
        }
        draw = new ol.interaction.Draw({
            features: features,
            type: type
        });
        map.addInteraction(draw);

        /**
         * 开始绘制
         */
        draw.on("drawstart", drawStart);

        /**
         * 结束绘制
         * 记录所有的点
         */
        draw.on("drawend", drawEnd);
    }

    /**
     * 删除额外添加的控件
     */
    function removeInteractions() {
        // 清除画笔控件
        map.removeInteraction(draw);
        // 清除修改控件
        map.removeInteraction(modify);
        removeSelectInteraction()
    }

    /**
     * 删除选中控件
     */
    function removeSelectInteraction() {
        // 清除选中状态
        select.getFeatures().clear();
        map.removeInteraction(select);
    }

    /**
     * 设置要素的坐标系统
     * @param features
     */
    function setFeatureGpsType(features) {
        var layer = getCurrentLayer();
        var isGcj02 = layer.get('isGcj02');
        features.set('gpsType', isGcj02 ? 1 : 2);
    }

    function getLength(feature) {
        var geometry = feature.getGeometry();
        var type = geometry.getType();
        var length = 0;
        var coordinates = [];

        if (type == 'MultiLineString') {
            var lineString = geometry.getLineString();
            coordinates = lineString.getCoordinates();
        } else if (type == 'LineString') {
            coordinates = geometry.getCoordinates();
        }

        if (coordinates.length > 0) {
            // 创建一个地形对象（椭圆），可用来计算两点之间的距离，不要问我6378137从哪里来的，我也不知道，这是一个神奇数字，估计是地球的半径吧
            var sphere = new ol.Sphere(6378137);

            var unit;
            for (var i = 0; i < coordinates.length - 1; i += 1) {
                // 计算两两之间的距离
                length += sphere.haversineDistance(coordinates[i], coordinates[i + 1]);
            }
            length = length / 1000;
            length = length.toFixed(5);

            currentFeature = feature;
            $('#MultiLineString_kilometre').val(length);
            $('#MultiLineString_kilometre').trigger('change');
        }
        return length;
    }


    /**
     * 展示、编辑要素属性
     * @param feature
     */
    function showFeatureProperties(feature) {
        currentFeature = feature;
        var geometry = feature.getGeometry();
        var type = geometry.getType();
        var properties = feature.getProperties();
        $.extend(properties, {
            altitude: 0,
            height: 0
        });
        var properties_dom = $("#properties");
        switch (type) {
            case "MultiLineString":
            case "LineString":
                /**
                 * 多线
                 * @type {*}
                 */
                var length = getLength(feature);
                console.log(length + 'km');
                $.extend(properties, {
                    kilometre: length
                });

                var interText = doT.template($("#MultiLineString").text());
                properties_dom.html(interText(properties));
                break;

            case "Point":
                /**
                 * 点
                 * @type {*}
                 */
                var interText = doT.template($("#Point").text());
                properties_dom.html(interText(properties));
                break;

            case "Polygon":
                /**
                 * 面
                 * @type {*}
                 */
                var interText = doT.template($("#Polygon").text());
                properties_dom.html(interText(properties));
                break;
        }
        featurePanelShow();
    }

    function fillForm(obj) {
        var form = $('#edit_panel').find('form');
        for (var key in obj) {
            $(form).find('[name=' + key + ']').val(obj[key] || '');
        }
    }

    /**
     * 显示要素编辑面板
     */
    function featurePanelShow() {
        $('#edit_panel').animate({
            left: '8px'
        }, 'fast');
    }

    /**
     * 关闭要素编辑面板
     */
    function featurePanelHide() {
        $('#edit_panel').animate({left: '-358px'}, 'fast', function () {
            $('#edit_panel').find('form')[0].reset();
        });
    }

    /**
     * 鼠标绘制开始
     * @param e
     */
    function drawStart(e) {
        is_drawing = true;
        $('.J_undo').removeClass('disabled');
    }

    /**
     * 绘制结束
     * @param e
     */
    function drawEnd(e) {
        is_drawing = false;
        $('.J_undo').addClass('disabled');
        var feature = e.feature;
        var timeStamp = new Date().getTime();
        feature.set("timestamp", timeStamp);

        setFeatureGpsType(feature);

        var geometry = feature.getGeometry();
        var type = geometry.getType();
        switch (type) {
            case 'Circle':
                // 圆
                var center = geometry.getCenter();
                var radius = geometry.getRadius();
                break;
            case 'Polygon':
                var coordinates = geometry.getCoordinates();
                // 面
                break;
            case 'LineString':
                // 线
                var coordinates = geometry.getCoordinates();
                break;
            case 'Point':
                var coordinates = geometry.getCoordinates();
                // 点
                break;
        }
        showFeatureProperties(feature);
    }


    function save(isPublish) {
        var gpxArray = DB.getArray('gpx');
        var geojsonArray = DB.getArray('geoJson');
        if (gpxArray.length == 0 || geojsonArray.length == 0) {
            return;
        }
        var data = {
            geoJsonStr: JSON.stringify(geojsonArray),
            gpxStr: JSON.stringify(gpxArray),
            isPublish: isPublish
        };
        $.post('save', data, function (res) {
            console.log(res);
            if (res) {
                // 保存成功，清空feature
                $.messager.show({
                    title: '温馨提示:',
                    msg: '保存成功!',
                    timeout: 1500,
                    showType: 'slide'
                });
                DB.removeFeatures();
                $.publish("history:delete");
            } else {
                // 保存失败
                $.messager.alert('错误:', '保存失败', 'error');
            }
        })
    }

    /**----------------------------------全局变量---------------------------------------*/
    window.is_drawing = function () {
        return is_drawing;
    };

});
